package com.fzrskj.cloud.free.user.utils.member;

import com.alibaba.fastjson.JSONObject;
import com.fzrskj.cloud.free.core.enums.DicParamEnum;
import com.fzrskj.cloud.free.core.enums.UserCertifyEnum;
import com.fzrskj.cloud.free.core.enums.UserStatusEnum;
import com.fzrskj.cloud.free.core.enums.UserTypeEnum;
import com.fzrskj.cloud.free.core.tool.CStrTool;
import com.fzrskj.cloud.free.dic.bean.DicVipgrade;
import com.fzrskj.cloud.free.dic.utils.DicParamUtils;
import com.fzrskj.cloud.free.dic.utils.DicVipgradeUtils;
import com.fzrskj.cloud.free.sys.utils.SendMailUtils;
import com.fzrskj.cloud.free.user.bean.UserAccount;
import com.fzrskj.cloud.free.user.bean.UserAccountData;
import com.fzrskj.cloud.free.user.dao.UserAccountDao;
import com.fzrskj.cloud.free.user.dao.UserAccountDataDao;
import com.fzrskj.cloud.free.user.service.member.vo.MemberImportItemVo;
import com.fzrskj.cloud.free.user.utils.UserAccountUtils;
import com.fzrskj.cloud.free.user.bean.UserAccountView;
import com.winiis.component.common.utils.bean.ClassUtils;
import ms.core.tool.StrTool;
import net.sf.json.JSONArray;
import org.apache.commons.collections.map.HashedMap;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * MemberImportUtils.
 *
 * @author zj.
 *         Created on 2019/5/8 0008.
 */
public class MemberImportUtils extends Object {
    /**
     * 预先过滤.
     * @param memberList member list.
     * @return member list.
     */
    public List<MemberImportItemVo> refer(List<MemberImportItemVo> memberList) {
        UserAccountUtils accountUtils = new UserAccountUtils();
        //遍历
        memberList.forEach(itemVo-> {
            System.out.print("Analysis line: ");
            System.out.println(itemVo);
            System.out.println("\n\n\n");
            //会员是否存在.
            UserAccount account = accountUtils.queryAccountByName(itemVo.getUserName());
            if (null != account) {
                itemVo.setRemark("已存在相同的会员账号");
                return;
            }
            //邮箱是否存在
            if (!StrTool.isBlankStr(itemVo.getEmail())) {
                UserAccountView accountView = accountUtils.queryUserAccountView(itemVo.getEmail());
                if (null != accountView) {
                    itemVo.setRemark("邮箱账号已被占用");
                    return;
                }
            }
            //手机号
            if (!StrTool.isBlankStr(itemVo.getMobile())) {
                UserAccountView mobile = accountUtils.queryUserAccountViewByMobile(itemVo.getMobile());
                if (null != mobile) {
                    itemVo.setRemark("手机号已被占用");
                    return;
                }
            }

            //会员等级
            DicVipgradeUtils vipgradeUtils = new DicVipgradeUtils();
            DicVipgrade vipgrade;
            if (!StrTool.isBlankStr(itemVo.getLevelName())) {
                vipgrade = vipgradeUtils.queryDicVipgradeByName(itemVo.getLevelName());
            } else {
                //取默认等级
                vipgrade = vipgradeUtils.queryDicVipgradeByCode(DicParamUtils.getParamValue(DicParamEnum.DEFAULT_USER_LEVEL.getVal()));
            }
            if (null == vipgrade) {
                itemVo.setRemark("会员等级不存在");
                return;
            }
            itemVo.setLevelCode(vipgrade.getLevelCode());
            itemVo.setLevelName(vipgrade.getLevelName());


            //格式化图片
            if (!StrTool.isBlankStr(itemVo.getCertFile())) {
                JSONArray files = new JSONArray();
                String[] fileArr = itemVo.getCertFile().split(",");
                for (String file : fileArr) {
                    files.add(file);
                }
                itemVo.setCertFileList(files);
            }

            itemVo.setRefer(1);
            itemVo.setRemark("待导入");
        });
        return memberList;
    }

    /**
     * 导入会员.
     * @param memberList member list.
     * @return member list.
     */
    public List<MemberImportItemVo> save(List<MemberImportItemVo> memberList) {
        UserAccountUtils accountUtils = new UserAccountUtils();
        UserAccountDao accountDao = new UserAccountDao();
        UserAccountDataDao dataDao = new UserAccountDataDao();

        //遍历
        memberList.forEach(itemVo-> {
            itemVo.setRefer(0);

            System.out.print("import line: ");
            System.out.println(itemVo);
            System.out.println("\n\n\n");

            //会员是否存在.
            UserAccount account = accountUtils.queryAccountByName(itemVo.getUserName());
            if (null != account) {
                itemVo.setRemark("已存在相同的会员账号");
                return;
            }
            //邮箱是否存在
            UserAccountView accountView = accountUtils.queryUserAccountView(itemVo.getEmail());
            if (null != accountView) {
                itemVo.setRemark("邮箱账号已被占用");
                return;
            }
            //手机号
            if (!StrTool.isBlankStr(itemVo.getMobile())) {
                UserAccountView mobile = accountUtils.queryUserAccountViewByMobile(itemVo.getMobile());
                if (null != mobile) {
                    itemVo.setRemark("手机号已被占用");
                    return;
                }
            }

            //会员等级
            DicVipgradeUtils vipgradeUtils = new DicVipgradeUtils();
            DicVipgrade vipgrade;
            if (!StrTool.isBlankStr(itemVo.getLevelName())) {
                vipgrade = vipgradeUtils.queryDicVipgradeByName(itemVo.getLevelName());
            } else {
                //取默认等级
                vipgrade = vipgradeUtils.queryDicVipgradeByCode(DicParamUtils.getParamValue(DicParamEnum.DEFAULT_USER_LEVEL.getVal()));
            }
            if (null == vipgrade) {
                itemVo.setRemark("会员等级不存在");
                return;
            }
            itemVo.setLevelCode(vipgrade.getLevelCode());
            itemVo.setLevelName(vipgrade.getLevelName());

            String password = "";
            if (!StrTool.isBlankStr(itemVo.getPassword())) {
                password = UserAccountUtils.encodePassword(itemVo.getPassword());
            } else if (!StrTool.isBlankStr(itemVo.getPasswordMd5())) {
                password = UserAccountUtils.encodePasswordFromMd5(itemVo.getPasswordMd5());
            } else {
                password = UserAccountUtils.encodePassword(CStrTool.randStr(8));
            }

            //添加账号记录
            UserAccount userAccount = new UserAccount();
            userAccount.setUserId(accountDao.getNewUserId());
            userAccount.setUserName(itemVo.getUserName());
            userAccount.setBalance(itemVo.getBalance());
            userAccount.setIntegral(0);
            userAccount.setPassword(password);
            userAccount.setStatus(UserStatusEnum.NORMAL.getStatus());
            userAccount.setLevelCode(itemVo.getLevelCode());
            userAccount.setRegTime(itemVo.getRegisterTime());
            userAccount.setRegIP(itemVo.getRegisterIp());
            userAccount.setLoginType(itemVo.getLoginType());
            userAccount.setOpenId(itemVo.getOpenId());
            Map<String, Object> newUser = ClassUtils.beanToMap(userAccount);
            newUser.remove("checkcode");
            newUser.remove("crmId");
            newUser.remove("csstId");
            Integer affect = accountDao.newUserAccount(newUser);
            if (affect < 1) {
                itemVo.setRemark("添加账号记录失败");
                return;
            }

            //添加账号数据
            UserAccountData accountData = new UserAccountData();
            accountData.setUserId(userAccount.getUserId());
            accountData.setUserName(userAccount.getUserName());
            accountData.setAddress(itemVo.getAddress());
            accountData.setCertCode(itemVo.getCertCode());
            accountData.setCertType("个人".equals(itemVo.getCertType()) ? String.valueOf(UserTypeEnum.INDIVIDUAL.getType()) : String.valueOf(UserTypeEnum.ORGANIZATION.getType()));
            accountData.setCityCode(itemVo.getCityCode());
            accountData.setCompanyName(itemVo.getCompanyName());
            accountData.setEmail(itemVo.getEmail());
            accountData.setFullName(itemVo.getFullName());
            accountData.setMobile(itemVo.getMobile());
            accountData.setProvinceCode(itemVo.getProvinceCode());
            accountData.setUserType(Integer.valueOf(accountData.getCertType()));
            accountData.setIsCertified("是".equals(itemVo.getIsCertified()) ? UserCertifyEnum.CERTIFIED.getState() : UserCertifyEnum.NEVER.getState());
            List<Map> fileList = new ArrayList<>();
            if (null != itemVo.getCertFileList() && !itemVo.getCertFileList().isEmpty()) {
                for (Object file : itemVo.getCertFileList()) {
                    Map<String, String> fileMap = new HashedMap();
                    fileMap.put("url", file.toString());
                    fileList.add(fileMap);
                }
            }
            accountData.setCertFile(JSONObject.toJSONString(fileList));
            affect = dataDao.addUserAccountData(ClassUtils.beanToMap(accountData));
            if (affect < 1) {
                itemVo.setRemark("添加账号数据失败");
                return;
            }

            //发送邮件提醒
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("\\[账号\\]", itemVo.getUserName()));
            params.add(new BasicNameValuePair("\\[密码\\]", password));
            String webUrl = DicParamUtils.getParamValue("weburl");
            params.add(new BasicNameValuePair("\\[网站\\]", webUrl));
            SendMailUtils mailUtils = new SendMailUtils();
            mailUtils.loadWebsiteParam(params);
            mailUtils.sendMail("userImportEmail", itemVo.getEmail(), params);

            itemVo.setRemark("导入成功");
        });
        return memberList;
    }
}
